package 手写;

public class 两个线程分别打印0到100之间的奇偶 {
    private static final Object LOCK = new Object();
    private static int i = 0;
    private static final int TOTAL = 100;

    public static void main(String[] args) {
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                while (i <= TOTAL) {
                    synchronized (LOCK) {
                        if (i % 2 == 1) {
                            System.out.println("thread1 " + i++);
                            LOCK.notify();
                        } else {
                            try {
                                LOCK.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        };

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                while (i <= TOTAL) {
                    synchronized (LOCK) {
                        if (i % 2 == 0) {
                            System.out.println("thread2 " + i++);
                            LOCK.notify();
                        } else {
                            try {
                                LOCK.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        };

        thread1.start();
        thread2.start();
    }
}
